import axios from "axios"

interface ApiGeneratorOptions {
  baseUrl: string
  token?: string
  apiTemplate?: string
  platform?: "yapi" | "apipost" | "swagger"
  projectId?: string
}

class ApiGenerator {
  private opts: ApiGeneratorOptions

  constructor(opts: ApiGeneratorOptions) {
    this.opts = opts
  }

  // 获取原始API数据
  public async fetchApiData() {
    const platform = this.opts.platform || "swagger"
    console.log(
      `正在从 ${this.opts.baseUrl} 获取${platform === "apipost" ? "APIPost" : platform === "swagger" ? "Swagger" : "YAPI"} API数据...`
    )

    try {
      if (platform === "swagger") {
        return await this.fetchSwaggerData()
      } else if (platform === "apipost") {
        return await this.fetchApipostData()
      } else {
        return await this.fetchYapiData()
      }
    } catch (error) {
      console.error("获取API数据失败:", error)
      throw error
    }
  }

  // 获取Swagger数据
  private async fetchSwaggerData() {
    const response = await axios.get(this.opts.baseUrl, {
      timeout: 10000,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

    if (!response.data) {
      throw new Error("Swagger API数据为空")
    }

    console.log("Swagger API数据获取成功")
    return { data: response.data }
  }

  // 获取APIPost数据（保留以防需要）
  private async fetchApipostData() {
    const response = await axios.get(this.opts.baseUrl, {
      timeout: 10000,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.opts.token}`
      }
    })

    if (!response.data) {
      throw new Error("APIPost API数据为空")
    }

    console.log("APIPost API数据获取成功")
    return { data: response.data }
  }

  // 获取YAPI数据（保留以防需要）
  private async fetchYapiData() {
    const response = await axios.get(this.opts.baseUrl, {
      timeout: 10000,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.opts.token}`
      }
    })

    if (!response.data) {
      throw new Error("YAPI API数据为空")
    }

    console.log("YAPI API数据获取成功")
    return { data: response.data }
  }
}

export default ApiGenerator
